<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>维修上报系统 - 管理端</title>
    
    <!-- Vue 3 CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
    
    <!-- Naive UI CDN -->
    <script src="https://cdn.jsdelivr.net/npm/naive-ui@2.34.4/dist/index.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/naive-ui@2.34.4/dist/index.css">
    
    <!-- 自定义样式 -->
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
        }
        
        .layout {
            min-height: 100vh;
        }
        
        .header {
            background: white;
            padding: 0 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .content {
            padding: 24px;
        }
        
        .page-header {
            background: white;
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 24px;
        }
        
        .page-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
            color: #333;
        }
        
        .page-description {
            margin: 8px 0 0 0;
            color: #666;
        }
        
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .card-header {
            padding: 16px 24px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .card-title {
            font-size: 16px;
            font-weight: 600;
            margin: 0;
        }
        
        .card-content {
            padding: 24px;
        }
        
        .toolbar {
            display: flex;
            gap: 12px;
            margin-bottom: 16px;
            flex-wrap: wrap;
        }
        
        .search-form {
            display: flex;
            gap: 12px;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .form-item {
            min-width: 200px;
        }
        
        @media (max-width: 768px) {
            .content {
                padding: 12px;
            }
            
            .search-form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .form-item {
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div id="app">
        <n-config-provider :theme="null">
            <n-message-provider>
                <n-dialog-provider>
                    <app-content></app-content>
                </n-dialog-provider>
            </n-message-provider>
        </n-config-provider>
    </div>
    
    <script>
        const { createApp } = Vue;
        const { NConfigProvider, NMessageProvider, NDialogProvider, NButton, NSelect, NInput, 
                NInputNumber, NDatePicker, NFormItem, NForm, NDataTable, NMenu, NModal, 
                NAlert, NUpload, useMessage, useDialog, zhCN, dateZhCN } = naive;
        
        // 主要内容组件
        const AppContent = {
            components: {
                NConfigProvider, NButton, NSelect, NInput, NInputNumber, NDatePicker, NFormItem, NForm, 
                NDataTable, NMenu, NModal, NAlert, NUpload
            },
            template: `
                <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
                <div class="layout">
                        <!-- 顶部导航 -->
                        <div class="header">
                            <h1 style="margin: 0; color: #333;">维修上报系统 - 管理端</h1>
                            <n-menu
                                mode="horizontal"
                                :options="menuOptions"
                                v-model:value="activeMenu"
                                @update:value="handleMenuSelect"
                            />
                        </div>
                        
                        <!-- 主要内容 -->
                        <div class="content">
                            <!-- 区域管理 -->
                            <div v-if="activeMenu === 'areas'">
                                <div class="page-header">
                                    <h2 class="page-title">区域管理</h2>
                                    <p class="page-description">管理系统中的区域信息</p>
                                </div>
                                
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">区域列表</h3>
                                        <n-button type="primary" @click="showAreaModal = true">
                                            添加区域
                                        </n-button>
                                    </div>
                                    <div class="card-content">
                                        <div class="toolbar">
                                            <n-input
                                                v-model:value="areaSearch"
                                                placeholder="搜索区域名称"
                                                style="width: 300px;"
                                                @keyup.enter="loadAreas"
                                            />
                                            <n-button @click="loadAreas">搜索</n-button>
                                        </div>
                                        
                                        <n-data-table
                                            :columns="areaColumns"
                                            :data="areas"
                                            :loading="areasLoading"
                                            :pagination="false"
                                        />
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 维修项目管理 -->
                            <div v-if="activeMenu === 'items'">
                                <div class="page-header">
                                    <h2 class="page-title">维修项目管理</h2>
                                    <p class="page-description">管理各区域的维修项目和价格</p>
                                </div>
                                
                                <!-- 区域统计 -->
                                <div class="card" style="margin-bottom: 16px;">
                                    <div class="card-header">
                                        <h3 class="card-title">区域数据统计</h3>
                                    </div>
                                    <div class="card-content">
                                        <div style="display: flex; flex-wrap: wrap; gap: 16px;">
                                            <div v-for="area in areas" :key="area.id" style="padding: 12px; border: 1px solid #e0e0e0; border-radius: 6px; min-width: 150px;">
                                                <div style="font-weight: bold; margin-bottom: 4px;">{{ area.name }}</div>
                                                <div style="color: #666;">项目数量: {{ areaStats[area.id]?.items || 0 }}</div>
                                                <div style="color: #666;">计价单数量: {{ areaStats[area.id]?.quotations || 0 }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">维修项目列表</h3>
                                        <div style="display: flex; gap: 12px;">
                                            <n-button @click="showImportModal = true">批量导入</n-button>
                                            <n-button type="primary" @click="showItemModal = true">
                                                添加项目
                                            </n-button>
                                            <n-button 
                                                type="error" 
                                                :disabled="selectedItemKeys.length === 0"
                                                @click="batchDeleteItems"
                                            >
                                                批量删除 ({{ selectedItemKeys.length }})
                                            </n-button>
                                        </div>
                                    </div>
                                    <div class="card-content">
                                        <div class="search-form">
                                            <div class="form-item">
                                                <n-form-item label="区域">
                                                    <n-select
                                                        v-model:value="itemFilters.area_id"
                                                        :options="areaOptions"
                                                        placeholder="选择区域"
                                                        clearable
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div class="form-item">
                                                <n-form-item label="搜索">
                                                    <n-input
                                                        v-model:value="itemFilters.search"
                                                        placeholder="搜索项目名称或规格"
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div>
                                                <n-button type="primary" @click="loadItems">搜索</n-button>
                                            </div>
                                        </div>
                                        
                                        <n-data-table
                                            :columns="itemColumns"
                                            :data="items"
                                            :loading="itemsLoading"
                                            :pagination="itemPagination"
                                            :remote="true"
                                            :checked-row-keys="selectedItemKeys"
                                            :row-key="row => row.id"
                                            @update:page="handleItemPageChange"
                                            @update:page-size="handleItemPageSizeChange"
                                            @update:checked-row-keys="handleItemSelectionChange"
                                        />
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 计价单管理 -->
                            <div v-if="activeMenu === 'quotations'">
                                <div class="page-header">
                                    <h2 class="page-title">计价单管理</h2>
                                    <p class="page-description">查看和导出计价单数据</p>
                                </div>
                                
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">计价单列表</h3>
                                        <n-button type="primary" @click="exportQuotations">
                                            导出Excel
                                        </n-button>
                                    </div>
                                    <div class="card-content">
                                        <div class="search-form">
                                            <div class="form-item">
                                                <n-form-item label="区域">
                                                    <n-select
                                                        v-model:value="quotationFilters.area_id"
                                                        :options="areaOptions"
                                                        placeholder="选择区域"
                                                        clearable
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div class="form-item">
                                                <n-form-item label="开始日期">
                                                    <n-date-picker
                                                        v-model:value="quotationFilters.start_date"
                                                        type="date"
                                                        placeholder="选择开始日期"
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div class="form-item">
                                                <n-form-item label="结束日期">
                                                    <n-date-picker
                                                        v-model:value="quotationFilters.end_date"
                                                        type="date"
                                                        placeholder="选择结束日期"
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div class="form-item">
                                                <n-form-item label="搜索">
                                                    <n-input
                                                        v-model:value="quotationFilters.search"
                                                        placeholder="搜索地点或人员"
                                                    />
                                                </n-form-item>
                                            </div>
                                            <div>
                                                <n-button type="primary" @click="loadQuotations">搜索</n-button>
                                            </div>
                                        </div>
                                        
                                        <n-data-table
                                            :columns="quotationColumns"
                                            :data="quotations"
                                            :loading="quotationsLoading"
                                            :pagination="quotationPagination"
                                            @update:page="handleQuotationPageChange"
                                            @update:page-size="handleQuotationPageSizeChange"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 区域编辑模态框 -->
                        <n-modal v-model:show="showAreaModal" preset="dialog" title="区域信息">
                            <n-form :model="areaForm" label-placement="left" label-width="80px">
                                <n-form-item label="区域名称" required>
                                    <n-input v-model:value="areaForm.name" placeholder="请输入区域名称" />
                                </n-form-item>
                                <n-form-item label="描述">
                                    <n-input
                                        v-model:value="areaForm.description"
                                        type="textarea"
                                        placeholder="请输入区域描述"
                                        :rows="3"
                                    />
                                </n-form-item>
                            </n-form>
                            <template #action>
                                <n-button @click="showAreaModal = false">取消</n-button>
                                <n-button type="primary" @click="saveArea" :loading="saving">保存</n-button>
                            </template>
                        </n-modal>
                        
                        <!-- 维修项目编辑模态框 -->
                        <n-modal v-model:show="showItemModal" preset="dialog" title="维修项目信息">
                            <n-form :model="itemForm" label-placement="left" label-width="80px">
                                <n-form-item label="所属区域" required>
                                    <n-select
                                        v-model:value="itemForm.area_id"
                                        :options="areaOptions"
                                        placeholder="请选择区域"
                                    />
                                </n-form-item>
                                <n-form-item label="项目名称" required>
                                    <n-input v-model:value="itemForm.name" placeholder="请输入项目名称" />
                                </n-form-item>
                                <n-form-item label="规格型号">
                                    <n-input v-model:value="itemForm.specification" placeholder="请输入规格型号" />
                                </n-form-item>
                                <n-form-item label="单位" required>
                                    <n-input v-model:value="itemForm.unit" placeholder="请输入单位" />
                                </n-form-item>
                                <n-form-item label="单价" required>
                                    <n-input-number
                                        v-model:value="itemForm.price"
                                        :min="0"
                                        :precision="2"
                                        placeholder="请输入单价"
                                        style="width: 100%;"
                                    />
                                </n-form-item>
                                <n-form-item label="备注">
                                    <n-input
                                        v-model:value="itemForm.remarks"
                                        type="textarea"
                                        placeholder="请输入备注"
                                        :rows="3"
                                    />
                                </n-form-item>
                            </n-form>
                            <template #action>
                                <n-button @click="showItemModal = false">取消</n-button>
                                <n-button type="primary" @click="saveItem" :loading="saving">保存</n-button>
                            </template>
                        </n-modal>
                        
                        <!-- 批量导入模态框 -->
                        <n-modal v-model:show="showImportModal" preset="dialog" title="批量导入维修项目">
                            <div style="margin-bottom: 16px;">
                                <n-alert type="info" title="导入说明">
                                    请选择CSV文件进行批量导入。文件应包含：维修内容、规格型号、单位、结算单价等列。
                                    <br>
                                    <n-button text type="primary" @click="downloadTemplate" style="margin-top: 8px;">
                                        下载导入模板
                                    </n-button>
                                </n-alert>
                            </div>
                            
                            <n-form :model="importForm" label-placement="left" label-width="80px">
                                <n-form-item label="目标区域" required>
                                    <n-select
                                        v-model:value="importForm.area_id"
                                        :options="importAreaOptions"
                                        placeholder="请选择导入到哪个区域"
                                        filterable
                                        tag
                                        @create="handleCreateArea"
                                    />
                                </n-form-item>
                                <n-form-item label="选择文件" required>
                                    <n-upload
                                        :file-list="importForm.fileList"
                                        @update:file-list="handleFileChange"
                                        accept=".csv"
                                        :max="1"
                                    >
                                        <n-button>选择CSV文件</n-button>
                                    </n-upload>
                                </n-form-item>
                            </n-form>
                            <template #action>
                                <n-button @click="showImportModal = false">取消</n-button>
                                <n-button type="primary" @click="importItems" :loading="importing">开始导入</n-button>
                            </template>
                        </n-modal>
                    </div>
                </div>
                </n-config-provider>
            `,
            setup() {
                 const message = useMessage();
                 const dialog = useDialog();
                
                // 响应式数据
                const activeMenu = Vue.ref('areas');
                const areas = Vue.ref([]);
                const items = Vue.ref([]);
                const quotations = Vue.ref([]);
                
                const areasLoading = Vue.ref(false);
                const itemsLoading = Vue.ref(false);
                const quotationsLoading = Vue.ref(false);
                const saving = Vue.ref(false);
                const importing = Vue.ref(false);
                
                const showAreaModal = Vue.ref(false);
                const showItemModal = Vue.ref(false);
                const showImportModal = Vue.ref(false);
                
                const areaSearch = Vue.ref('');
                const areaForm = Vue.ref({ id: null, name: '', description: '' });
                const itemForm = Vue.ref({ id: null, area_id: null, name: '', specification: '', unit: '', price: 0, remarks: '' });
                const importForm = Vue.ref({ area_id: null, fileList: [] });
                
                const itemFilters = Vue.ref({ area_id: null, search: '', page: 1, limit: 20 });
                const quotationFilters = Vue.ref({ area_id: null, start_date: null, end_date: null, search: '', page: 1, limit: 20 });
                
                const itemPagination = Vue.ref({ page: 1, pageSize: 20, itemCount: 0, showSizePicker: true, pageSizes: [10, 20, 50] });
                const quotationPagination = Vue.ref({ page: 1, pageSize: 20, itemCount: 0, showSizePicker: true, pageSizes: [10, 20, 50] });
                
                const selectedItemKeys = Vue.ref([]);
                const areaStats = Vue.ref({});
                
                // 计算属性
                const menuOptions = Vue.computed(() => [
                    { label: '区域管理', key: 'areas' },
                    { label: '维修项目', key: 'items' },
                    { label: '计价单', key: 'quotations' }
                ]);
                
                const areaOptions = Vue.computed(() => [
                    { label: '全部区域', value: null },
                    ...areas.value.map(area => ({ label: area.name, value: area.id }))
                ]);
                
                const importAreaOptions = Vue.computed(() => [
                    ...areas.value.map(area => ({ label: area.name, value: area.id }))
                ]);
                
                const areaColumns = Vue.computed(() => [
                    { title: 'ID', key: 'id', width: 80 },
                    { title: '区域名称', key: 'name' },
                    { title: '描述', key: 'description' },
                    {
                        title: '操作',
                        key: 'actions',
                        width: 150,
                        render: (row) => {
                            return Vue.h('div', { style: 'display: flex; gap: 8px;' }, [
                                Vue.h(NButton, {
                                    size: 'small',
                                    onClick: () => editArea(row)
                                }, { default: () => '编辑' }),
                                Vue.h(NButton, {
                                    size: 'small',
                                    type: 'error',
                                    onClick: () => deleteArea(row)
                                }, { default: () => '删除' })
                            ]);
                        }
                    }
                ]);
                
                const itemColumns = Vue.computed(() => [
                    {
                        type: 'selection',
                        width: 50
                    },
                    { title: 'ID', key: 'id', width: 80 },
                    { title: '区域', key: 'area_name', width: 120 },
                    { title: '项目名称', key: 'name' },
                    { title: '规格型号', key: 'specification' },
                    { title: '单位', key: 'unit', width: 80 },
                    { title: '单价(元)', key: 'price', width: 100 },
                    {
                        title: '操作',
                        key: 'actions',
                        width: 150,
                        render: (row) => {
                            return Vue.h('div', { style: 'display: flex; gap: 8px;' }, [
                                Vue.h(NButton, {
                                    size: 'small',
                                    onClick: () => editItem(row)
                                }, { default: () => '编辑' }),
                                Vue.h(NButton, {
                                    size: 'small',
                                    type: 'error',
                                    onClick: () => deleteItem(row)
                                }, { default: () => '删除' })
                            ]);
                        }
                    }
                ]);
                
                const quotationColumns = Vue.computed(() => [
                    { title: 'ID', key: 'id', width: 80 },
                    { title: '区域', key: 'area_name', width: 120 },
                    { title: '维修地点', key: 'location' },
                    { title: '维修人员', key: 'person', width: 100 },
                    { title: '维修时间', key: 'repair_date', width: 120 },
                    { title: '总价(元)', key: 'total_price', width: 100 },
                    { title: '提交时间', key: 'created_at', width: 150 },
                    {
                        title: '操作',
                        key: 'actions',
                        width: 100,
                        render: (row) => {
                            return Vue.h(NButton, {
                                size: 'small',
                                type: 'error',
                                onClick: () => deleteQuotation(row)
                            }, { default: () => '删除' });
                        }
                    }
                ]);
                
                // 方法
                const handleMenuSelect = (key) => {
                    activeMenu.value = key;
                    if (key === 'areas') {
                        loadAreas();
                    } else if (key === 'items') {
                        loadItems();
                    } else if (key === 'quotations') {
                        loadQuotations();
                    }
                };
                
                const loadAreas = async () => {
                    try {
                        areasLoading.value = true;
                        const params = new URLSearchParams();
                        if (areaSearch.value) params.append('search', areaSearch.value);
                        
                        const response = await fetch(`/api/admin/areas?${params}`);
                        const result = await response.json();
                        
                        if (result.success) {
                            areas.value = result.data;
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('获取区域列表失败');
                    } finally {
                        areasLoading.value = false;
                    }
                };
                
                const loadItems = async () => {
                    try {
                        itemsLoading.value = true;
                        const params = new URLSearchParams();
                        if (itemFilters.value.area_id) params.append('area_id', itemFilters.value.area_id);
                        if (itemFilters.value.search) params.append('search', itemFilters.value.search);
                        params.append('page', itemFilters.value.page);
                        params.append('limit', itemFilters.value.limit);
                        
                        const response = await fetch(`/api/admin/items?${params}`);
                        const result = await response.json();
                        
                        if (result.success) {
                            items.value = result.data.items;
                            itemPagination.value.itemCount = result.data.total;
                        itemPagination.value.page = result.data.page;
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('获取维修项目失败');
                    } finally {
                        itemsLoading.value = false;
                    }
                };
                
                const loadAreaStats = async () => {
                    try {
                        const response = await fetch('/api/admin/area-stats');
                        const result = await response.json();
                        
                        if (result.success) {
                            areaStats.value = result.data;
                        }
                    } catch (error) {
                        console.error('获取区域统计失败:', error);
                    }
                };
                
                const loadQuotations = async () => {
                    try {
                        quotationsLoading.value = true;
                        const params = new URLSearchParams();
                        if (quotationFilters.value.area_id) params.append('area_id', quotationFilters.value.area_id);
                        if (quotationFilters.value.start_date) params.append('start_date', formatDate(quotationFilters.value.start_date));
                        if (quotationFilters.value.end_date) params.append('end_date', formatDate(quotationFilters.value.end_date));
                        if (quotationFilters.value.search) params.append('search', quotationFilters.value.search);
                        params.append('page', quotationFilters.value.page);
                        params.append('limit', quotationFilters.value.limit);
                        
                        const response = await fetch(`/api/admin/quotations?${params}`);
                        const result = await response.json();
                        
                        if (result.success) {
                            quotations.value = result.data.quotations;
                            quotationPagination.value.itemCount = result.data.total;
                        quotationPagination.value.page = result.data.page;
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('获取计价单失败');
                    } finally {
                        quotationsLoading.value = false;
                    }
                };
                
                const formatDate = (timestamp) => {
                    if (!timestamp) return '';
                    const date = new Date(timestamp);
                    return date.toISOString().split('T')[0];
                };
                
                const editArea = (area) => {
                    areaForm.value = { ...area };
                    showAreaModal.value = true;
                };
                
                const deleteArea = (area) => {
                    dialog.warning({
                        title: '确认删除',
                        content: `确定要删除区域"${area.name}"吗？`,
                        positiveText: '删除',
                        negativeText: '取消',
                        onPositiveClick: async () => {
                            try {
                                const response = await fetch(`/api/admin/areas/${area.id}`, {
                                    method: 'DELETE'
                                });
                                const result = await response.json();
                                
                                if (result.success) {
                                    message.success('删除成功');
                                    loadAreas();
                                } else {
                                    message.error(result.message);
                                }
                            } catch (error) {
                                message.error('删除失败');
                            }
                        }
                    });
                };
                
                const saveArea = async () => {
                    try {
                        saving.value = true;
                        const isEdit = !!areaForm.value.id;
                        const url = isEdit ? `/api/admin/areas/${areaForm.value.id}` : '/api/admin/areas';
                        const method = isEdit ? 'PUT' : 'POST';
                        
                        const response = await fetch(url, {
                            method,
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(areaForm.value)
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success(isEdit ? '更新成功' : '添加成功');
                            showAreaModal.value = false;
                            areaForm.value = { id: null, name: '', description: '' };
                            loadAreas();
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('保存失败');
                    } finally {
                        saving.value = false;
                    }
                };
                
                const editItem = (item) => {
                    itemForm.value = { ...item };
                    showItemModal.value = true;
                };
                
                const deleteItem = (item) => {
                    dialog.warning({
                        title: '确认删除',
                        content: `确定要删除维修项目"${item.name}"吗？`,
                        positiveText: '删除',
                        negativeText: '取消',
                        onPositiveClick: async () => {
                            try {
                                const response = await fetch(`/api/admin/items/${item.id}`, {
                                    method: 'DELETE'
                                });
                                const result = await response.json();
                                
                                if (result.success) {
                                    message.success('删除成功');
                                    loadItems();
                                    loadAreaStats();
                                } else {
                                    message.error(result.message);
                                }
                            } catch (error) {
                                message.error('删除失败');
                            }
                        }
                    });
                };
                
                const deleteQuotation = (quotation) => {
                    dialog.warning({
                        title: '确认删除',
                        content: `确定要删除计价单"${quotation.location}"吗？`,
                        positiveText: '删除',
                        negativeText: '取消',
                        onPositiveClick: async () => {
                            try {
                                const response = await fetch(`/api/admin/quotations/${quotation.id}`, {
                                    method: 'DELETE'
                                });
                                const result = await response.json();
                                
                                if (result.success) {
                                    message.success('删除成功');
                                    loadQuotations();
                                } else {
                                    message.error(result.message);
                                }
                            } catch (error) {
                                message.error('删除失败');
                            }
                        }
                    });
                };
                
                const saveItem = async () => {
                    try {
                        saving.value = true;
                        const isEdit = !!itemForm.value.id;
                        const url = isEdit ? `/api/admin/items/${itemForm.value.id}` : '/api/admin/items';
                        const method = isEdit ? 'PUT' : 'POST';
                        
                        const response = await fetch(url, {
                            method,
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(itemForm.value)
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success(isEdit ? '更新成功' : '添加成功');
                            showItemModal.value = false;
                            itemForm.value = { id: null, area_id: null, name: '', specification: '', unit: '', price: 0, remarks: '' };
                            loadItems();
                            loadAreaStats();
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('保存失败');
                    } finally {
                        saving.value = false;
                    }
                };
                
                const handleFileChange = (fileList) => {
                    importForm.value.fileList = fileList;
                };
                
                const downloadTemplate = () => {
                    window.open('/api/admin/template', '_blank');
                };
                
                const handleCreateArea = async (areaName) => {
                    try {
                        const response = await fetch('/api/admin/areas', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ name: areaName })
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success('新区域创建成功');
                            await loadAreas();
                            importForm.value.area_id = result.data.id;
                            return { label: areaName, value: result.data.id };
                        } else {
                            message.error(result.message);
                            return false;
                        }
                    } catch (error) {
                        message.error('创建区域失败');
                        return false;
                    }
                };
                
                /**
                 * 导入维修项目
                 * 使用异步方式提交，避免页面刷新
                 */
                const importItems = async (event) => {
                    // 阻止默认的表单提交行为，避免页面刷新
                    if (event && event.preventDefault) {
                        event.preventDefault();
                    }
                    
                    try {
                        if (!importForm.value.area_id || !importForm.value.fileList.length) {
                            message.error('请选择区域和文件');
                            return false;
                        }
                        
                        importing.value = true;
                        const formData = new FormData();
                        formData.append('area_id', importForm.value.area_id);
                        formData.append('file', importForm.value.fileList[0].file);
                        
                        const response = await fetch('/api/admin/items/import', {
                            method: 'POST',
                            body: formData
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success(result.message);
                            showImportModal.value = false;
                            importForm.value = { area_id: null, fileList: [] };
                            loadItems();
                            loadAreaStats();
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('导入失败');
                    } finally {
                        importing.value = false;
                    }
                    
                    // 确保不会有页面跳转或刷新
                    return false;
                };
                
                const exportQuotations = async () => {
                    try {
                        const exportData = {
                            area_id: quotationFilters.value.area_id,
                            start_date: quotationFilters.value.start_date ? formatDate(quotationFilters.value.start_date) : null,
                            end_date: quotationFilters.value.end_date ? formatDate(quotationFilters.value.end_date) : null,
                            search: quotationFilters.value.search
                        };
                        
                        const response = await fetch('/api/admin/quotations/export', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(exportData)
                        });
                        
                        const result = await response.json();
                        
                        if (result.success) {
                            message.success(`导出成功，共${result.data.count}条记录`);
                            // 下载文件
                            window.open(result.data.downloadUrl, '_blank');
                        } else {
                            message.error(result.message);
                        }
                    } catch (error) {
                        message.error('导出失败');
                    }
                };
                
                const handleItemPageChange = (page) => {
                    itemFilters.value.page = page;
                    itemPagination.value.page = page;
                    loadItems();
                };
                
                const handleItemPageSizeChange = (pageSize) => {
                    itemFilters.value.limit = pageSize;
                    itemFilters.value.page = 1;
                    itemPagination.value.pageSize = pageSize;
                    itemPagination.value.page = 1;
                    loadItems();
                };
                
                const handleQuotationPageChange = (page) => {
                    quotationFilters.value.page = page;
                    quotationPagination.value.page = page;
                    loadQuotations();
                };
                
                const handleQuotationPageSizeChange = (pageSize) => {
                    quotationFilters.value.limit = pageSize;
                    quotationFilters.value.page = 1;
                    quotationPagination.value.pageSize = pageSize;
                    quotationPagination.value.page = 1;
                    loadQuotations();
                };
                
                const handleItemSelectionChange = (keys) => {
                    selectedItemKeys.value = keys;
                };
                
                /**
                 * 批量删除维修项目
                 * 使用异步方式提交，避免页面刷新
                 */
                const batchDeleteItems = async (event) => {
                    // 阻止默认的表单提交行为，避免页面刷新
                    if (event && event.preventDefault) {
                        event.preventDefault();
                    }
                    
                    if (selectedItemKeys.value.length === 0) {
                        message.warning('请选择要删除的项目');
                        return false;
                    }
                    
                    dialog.warning({
                        title: '确认删除',
                        content: `确定要删除选中的 ${selectedItemKeys.value.length} 个项目吗？`,
                        positiveText: '确定',
                        negativeText: '取消',
                        onPositiveClick: async () => {
                            try {
                                const response = await fetch('/api/admin/items/batch-delete', {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({ ids: selectedItemKeys.value })
                                });
                                const result = await response.json();
                                if (result.success) {
                                    message.success('批量删除成功');
                                    selectedItemKeys.value = [];
                                    loadItems();
                                    loadAreaStats();
                                } else {
                                    message.error(result.message);
                                }
                            } catch (error) {
                                message.error('删除失败');
                            }
                        }
                    });
                    
                    // 确保不会有页面跳转或刷新
                    return false;
                };
                
                // 初始化
                Vue.onMounted(() => {
                    loadAreas();
                    loadAreaStats();
                });
                
                return {
                    activeMenu,
                    menuOptions,
                    areas,
                    items,
                    quotations,
                    areasLoading,
                    itemsLoading,
                    quotationsLoading,
                    saving,
                    importing,
                    showAreaModal,
                    showItemModal,
                    showImportModal,
                    areaSearch,
                    areaForm,
                    itemForm,
                    importForm,
                    itemFilters,
                    quotationFilters,
                    itemPagination,
                    quotationPagination,
                    areaOptions,
                    importAreaOptions,
                    areaColumns,
                    itemColumns,
                    quotationColumns,
                    handleMenuSelect,
                    loadAreas,
                    loadItems,
                    loadQuotations,
                    editArea,
                    deleteArea,
                    saveArea,
                    editItem,
                    deleteItem,
                    deleteQuotation,
                    saveItem,
                    handleFileChange,
                    downloadTemplate,
                    handleCreateArea,
                    importItems,
                    exportQuotations,
                    handleItemPageChange,
                    handleItemPageSizeChange,
                    handleQuotationPageChange,
                    handleQuotationPageSizeChange,
                    selectedItemKeys,
                    areaStats,
                    handleItemSelectionChange,
                    batchDeleteItems,
                    loadAreaStats,
                    zhCN,
                    dateZhCN
                };
            }
        };
        
        // 创建Vue应用
        createApp({
            components: {
                NConfigProvider,
                NMessageProvider,
                NDialogProvider,
                AppContent
            }
        }).mount('#app');
    </script>
</body>
</html>